﻿/*
 * Created by SharpDevelop.
 * User: wxm
 * Date: 2014/1/18
 * Time: 0:23
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;
using StructureMap;
using AllInOne;

namespace CommunityGuider
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        internal static extern Boolean AllocConsole();

		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
            if (IsAlreadyRunning()) return;

            if (args.Length > 0 && args[0].Equals("win", StringComparison.OrdinalIgnoreCase))
            {

                //Application.Run(new MainForm());
            }
            else
            {
                AllocConsole();
                //new MainConsole().Start();
            }

            ObjectFactory.Configure(x =>
            {
                x.For<IHomePage>().ConditionallyUse(c =>
                {
                    c.If(ctx=> System.Configuration.ConfigurationManager.AppSettings["console"] == "True")
                        .ThenIt.Is.ConstructedBy(_=> new ConsoleHome());

                    c.TheDefault.Is.ConstructedBy(_ => new SimpleHome());
                });

                x.For<ISampleReader>().Use<SimpleSampleReader>();
            });

            var home = ObjectFactory.GetInstance<IHomePage>();

            var mainForm = home as Form;
            if (mainForm != null)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(mainForm);
            }
            else
            {
                home.Show();
            }
        }

        #region Check Opened
        private static bool IsAlreadyRunning()
        {
            string sExeName = System.IO.Path.GetFileName(Application.ExecutablePath);
            bool bCreatedNew;

            var mutex = new System.Threading.Mutex(true, sExeName, out bCreatedNew);
            if (bCreatedNew)
                mutex.ReleaseMutex();

            return !bCreatedNew;
        }
        #endregion
    }
}
